import type { TdOptionProps } from 'tdesign-vue-next'
import type { WatchSource } from 'vue'
import { onMounted, ref, watch } from 'vue'

export default function useSearchSelect<T>(
  source: WatchSource<T>,
  watchGetFn: (value: T) => TdOptionProps | Promise<TdOptionProps>,
  searchFn: (query: string) => TdOptionProps[] | Promise<TdOptionProps[]>,
) {
  const selectOptions = ref<TdOptionProps[]>([])
  watch(source, (value) => {
    if (value) {
      const result = watchGetFn(value)
      if (result instanceof Promise) {
        result.then((res) => {
          selectOptions.value.findIndex(item => item.value === value) === -1 && selectOptions.value.push(res)
        })
      }
      else {
        selectOptions.value.findIndex(item => item.value === value) === -1 && selectOptions.value.push(result)
      }
    }
  })
  const searchLoading = ref(false)
  function handleSearch(query: string) {
    searchLoading.value = true
    const result = searchFn(query)
    if (result instanceof Promise) {
      result.then((res) => {
        selectOptions.value = res
      }).finally(() => {
        searchLoading.value = false
      })
    }
    else {
      selectOptions.value = result
      searchLoading.value = false
    }
  }
  onMounted(() => {
    handleSearch('')
  })
  return { selectOptions, searchLoading, handleSearch }
}
